package com.zmn.plat.admin.controller.part;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;
import com.zmn.common.constant.StatusConsts;
import com.zmn.common.dto.LayuiTableResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.office.ExcelCell;
import com.zmn.common.utils.office.ExcelUtil;
import com.zmn.mcc.cas.web.StaffAdminService;
import com.zmn.plat.model.entity.part.PartSkuQuery;
import com.zmn.plat.model.vo.part.PartSkuVO;

import lombok.extern.log4j.Log4j;

/**
 * 类描述：
 *
 * @author DaiZhichao
 * @since 2018/11/5 16:52
 */
@RestController
@RequestMapping("/part/ajax")
@Log4j
public class PartSkuAjaxController extends PartBaseController {

    private Logger logger = LoggerFactory.getLogger(PartSkuAjaxController.class);

    /**
     * 描述: 返回table数据【配件列表】
     *
     * @author DaiZhichao
     * @since 2018/11/5 16:52
     */
    @RequestMapping(value = "/list", produces = "application/json; charset=utf-8")
    public LayuiTableResponseDTO purchaseApplyList(PartSkuQuery query) {
        Integer count = partSkuService.countByQuery(query);
        List<PartSkuVO> partSkuVOList = partSkuService.listVOPageByQuery(query);
        AtomicReference<Integer> index = new AtomicReference<>(0);
        partSkuVOList.forEach(item -> item.setLayIndex(index.getAndSet(index.get() + 1)));

        return new LayuiTableResponseDTO<>(StatusConsts.STATUS_SUCCESS, "OK", count, partSkuVOList);
    }

    private static final String PLAT_PART_FILE_NAME = "[%s]配件列表.xlsx";
    private static final String[] PLAT_PART_BASE_HEAD =
        {"ID", "配件一级分类", "配件二级分类", "配件名称", "厂家配件名称", "品牌", "单位", "包装规格", "总公司采购单价", "子公司采购单价", "配件图片1", "配件图片2", "配件图片3", "配件图片4"};
    private static final String[] PLAT_PART_BASE_HEAD_TWO =
        {"ID", "配件一级分类", "配件二级分类", "配件名称", "厂家配件名称", "品牌", "单位", "包装规格", "配件图片1", "配件图片2", "配件图片3", "配件图片4"};

    /**
     * 描述: 表格数据导出【按照配件分类导出配件】已废弃
     *
     * @since 2019/03/07 15:42
     */
    @Deprecated
    @RequestMapping(value = "/exportExcelByCategId")
    public ResponseEntity exportExcelByCategId(Integer categId) throws IOException {

        ArrayList<PartSkuVO> objects = Lists.newArrayList();
        List<PartSkuVO> allPart = partSkuBService.getAllPart(objects, categId);

        return baseExportPartSkuVO(allPart);
    }

    /**
     * 描述: 表格数据导出【从页面Query导出配件】
     *
     * @since 2019/03/07 15:42
     */
    @RequestMapping(value = "/exportExcel")
    public ResponseEntity exportExcel(PartSkuQuery query) throws IOException {

        Integer exportLimit = getMcStaff().getExportLimit();

        if (NumberUtil.isPositiveInteger(exportLimit)) {
            query.setPageNum(1);
            query.setPageSize(exportLimit);
        } else {
            return alterMsgWithExportExcel();
        }
        List<PartSkuVO> partSkuVOList = partSkuService.listVOPageByQuery(query);

        return baseExportPartSkuVO(partSkuVOList);
    }

    /**
     * 描述: 配件表格数据导出Base方法
     *
     * @since 2019/03/08 15:55
     */
    @NotNull
    private ResponseEntity<byte[]> baseExportPartSkuVO(List<PartSkuVO> allPart) throws IOException {
        // 主逻辑拼接数据
        String nowFormatted = DateUtil.getNowFormatted(DateUtil.FORMAT_DATE2);
        String fileName = String.format(PLAT_PART_FILE_NAME, nowFormatted);
        LinkedList<LinkedList<ExcelCell<Integer, String>>> rowList = Lists.newLinkedList();
        boolean showHq = StaffAdminService.isPermitted("/part/price/showHq.action");
        boolean showSub = StaffAdminService.isPermitted("/part/price/showSub.action");
        LinkedList<ExcelCell<Integer, String>> title =
            Stream.of(PLAT_PART_BASE_HEAD).filter(p -> (!p.equals("总公司采购单价") || showHq) && (!p.equals("子公司采购单价") || showSub))
                .map(str -> ExcelCell.of(0, str, str)).collect(Collectors.toCollection(LinkedList::new));
        rowList.addFirst(title);

        int[] index = {1};
        rowList.addAll(allPart.stream().map(partSkuVO -> {
            LinkedList<ExcelCell<Integer, String>> row = Lists.newLinkedList();
            row.add(ExcelCell.of(index[0], "ID", String.valueOf(partSkuVO.getSkuId())));
            row.add(ExcelCell.of(index[0], "配件一级分类", partSkuVO.getCategOneName()));
            row.add(ExcelCell.of(index[0], "配件二级分类", partSkuVO.getCategName()));
            row.add(ExcelCell.of(index[0], "配件名称", partSkuVO.getName()));
            row.add(ExcelCell.of(index[0], "厂家配件名称", partSkuVO.getFactoryName()));
            row.add(ExcelCell.of(index[0], "品牌", partSkuVO.getBrandName()));
            row.add(ExcelCell.of(index[0], "单位", partSkuVO.getUnit()));
            row.add(ExcelCell.of(index[0], "包装规格", partSkuVO.getPackSpec()));

            if (showHq) {
                row.add(ExcelCell.of(index[0], "总公司采购单价", partSkuVO.getHqPurchasePriceStr()));
            }
            if (showSub) {
                row.add(ExcelCell.of(index[0], "子公司采购单价", partSkuVO.getSubPurchasePriceStr()));
            }

            row.add(ExcelCell.of(index[0], "配件图片1", partSkuVO.getImgSrc()));
            row.add(ExcelCell.of(index[0], "配件图片2", partSkuVO.getImgSrc2()));
            row.add(ExcelCell.of(index[0], "配件图片3", partSkuVO.getImgSrc3()));
            row.add(ExcelCell.of(index[0], "配件图片4", partSkuVO.getImgSrc4()));
            index[0]++;
            return row;
        }).collect(Collectors.toCollection(LinkedList::new)));

        // 准备数据表
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet(nowFormatted);

        // 导出数据
        ExcelUtil.writeSheet(rowList, sheet);
        // 表格导出
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        workbook.write(stream);
        stream.close();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, "UTF-8"));
        headers.setContentType(MediaType.valueOf("application/msexcel"));
        headers.setAcceptCharset(Lists.newArrayList(Charset.forName("UTF-8")));
        return ResponseEntity.ok().headers(headers).body(stream.toByteArray());
    }
}
